//
//  SwiftUIModelExamples.swift
//  swiftuitest
//
//  SwiftUI Model 完整示例集合
//

import SwiftUI
import Combine

// MARK: - 1. 基础 ObservableObject 模型

/// 基础计数器模型
class CounterModel: ObservableObject {
    @Published var count: Int = 0
    @Published var isRunning: Bool = false
    
    func increment() {
        count += 1
    }
    
    func decrement() {
        count -= 1
    }
    
    func reset() {
        count = 0
    }
}

/// 基础计数器视图
struct CounterModelView: View {
    @StateObject private var model = CounterModel()
    
    var body: some View {
        VStack(spacing: 20) {
            Text("计数: \(model.count)")
                .font(.largeTitle)
            
            HStack(spacing: 20) {
                Button("减少") {
                    model.decrement()
                }
                .buttonStyle(.bordered)
                
                Button("重置") {
                    model.reset()
                }
                .buttonStyle(.bordered)
                
                Button("增加") {
                    model.increment()
                }
                .buttonStyle(.borderedProminent)
            }
            
            Toggle("运行中", isOn: $model.isRunning)
        }
        .padding()
    }
}

// MARK: - 2. 用户信息模型

/// 用户信息模型
class UserModel: ObservableObject {
    @Published var id: UUID = UUID()
    @Published var name: String = ""
    @Published var email: String = ""
    @Published var age: Int = 0
    @Published var isActive: Bool = true
    
    // 计算属性
    var isValid: Bool {
        !name.isEmpty && !email.isEmpty && email.contains("@")
    }
    
    // 方法
    func updateName(_ newName: String) {
        name = newName
    }
    
    func activate() {
        isActive = true
    }
    
    func deactivate() {
        isActive = false
    }
}

/// 用户信息视图
struct UserModelView: View {
    @StateObject private var user = UserModel()
    
    var body: some View {
        Form {
            Section("基本信息") {
                TextField("姓名", text: $user.name)
                TextField("邮箱", text: $user.email)
                    .keyboardType(.emailAddress)
                Stepper("年龄: \(user.age)", value: $user.age, in: 0...120)
            }
            
            Section("状态") {
                Toggle("激活", isOn: $user.isActive)
                
                if user.isValid {
                    Label("信息有效", systemImage: "checkmark.circle.fill")
                        .foregroundColor(.green)
                } else {
                    Label("信息无效", systemImage: "xmark.circle.fill")
                        .foregroundColor(.red)
                }
            }
            
            Section("操作") {
                Button("激活") {
                    user.activate()
                }
                
                Button("停用") {
                    user.deactivate()
                }
            }
        }
    }
}

// MARK: - 3. 待办事项模型

/// 待办事项项目
struct TodoItem: Identifiable, Codable {
    var id: UUID = UUID()
    var title: String
    var isCompleted: Bool = false
    var createdAt: Date = Date()
    var priority: Priority = .medium
    
    enum Priority: String, Codable, CaseIterable {
        case low = "低"
        case medium = "中"
        case high = "高"
    }
}

/// 待办事项列表模型
class TodoListModel: ObservableObject {
    @Published var todos: [TodoItem] = []
    @Published var filter: FilterType = .all
    
    enum FilterType: String, CaseIterable {
        case all = "全部"
        case active = "未完成"
        case completed = "已完成"
    }
    
    // 计算属性
    var filteredTodos: [TodoItem] {
        switch filter {
        case .all:
            return todos
        case .active:
            return todos.filter { !$0.isCompleted }
        case .completed:
            return todos.filter { $0.isCompleted }
        }
    }
    
    var completedCount: Int {
        todos.filter { $0.isCompleted }.count
    }
    
    var activeCount: Int {
        todos.filter { !$0.isCompleted }.count
    }
    
    // 方法
    func addTodo(_ title: String, priority: TodoItem.Priority = .medium) {
        let newTodo = TodoItem(title: title, priority: priority)
        todos.append(newTodo)
    }
    
    func toggleTodo(_ todo: TodoItem) {
        if let index = todos.firstIndex(where: { $0.id == todo.id }) {
            todos[index].isCompleted.toggle()
        }
    }
    
    func deleteTodo(_ todo: TodoItem) {
        todos.removeAll { $0.id == todo.id }
    }
    
    func deleteCompleted() {
        todos.removeAll { $0.isCompleted }
    }
}

/// 待办事项视图
struct TodoListModelView: View {
    @StateObject private var model = TodoListModel()
    @State private var newTodoTitle = ""
    @State private var selectedPriority: TodoItem.Priority = .medium
    
    var body: some View {
        NavigationView {
            VStack {
                // 统计信息
                HStack {
                    VStack {
                        Text("\(model.activeCount)")
                            .font(.title)
                        Text("未完成")
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                    .frame(maxWidth: .infinity)
                    
                    Divider()
                    
                    VStack {
                        Text("\(model.completedCount)")
                            .font(.title)
                        Text("已完成")
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                    .frame(maxWidth: .infinity)
                }
                .padding()
                .background(Color.gray.opacity(0.1))
                .cornerRadius(10)
                .padding(.horizontal)
                
                // 过滤器
                Picker("过滤", selection: $model.filter) {
                    ForEach(TodoListModel.FilterType.allCases, id: \.self) { type in
                        Text(type.rawValue).tag(type)
                    }
                }
                .pickerStyle(.segmented)
                .padding(.horizontal)
                
                // 列表
                List {
                    ForEach(model.filteredTodos) { todo in
                        HStack {
                            Button {
                                model.toggleTodo(todo)
                            } label: {
                                Image(systemName: todo.isCompleted ? "checkmark.circle.fill" : "circle")
                                    .foregroundColor(todo.isCompleted ? .green : .gray)
                            }
                            .buttonStyle(.plain)
                            
                            VStack(alignment: .leading) {
                                Text(todo.title)
                                    .strikethrough(todo.isCompleted)
                                    .foregroundColor(todo.isCompleted ? .secondary : .primary)
                                
                                HStack {
                                    Text(todo.priority.rawValue)
                                        .font(.caption)
                                        .padding(.horizontal, 8)
                                        .padding(.vertical, 2)
                                        .background(priorityColor(todo.priority))
                                        .cornerRadius(4)
                                }
                            }
                            
                            Spacer()
                        }
                        .swipeActions {
                            Button(role: .destructive) {
                                model.deleteTodo(todo)
                            } label: {
                                Label("删除", systemImage: "trash")
                            }
                        }
                    }
                }
                
                // 添加新待办
                HStack {
                    TextField("新待办事项", text: $newTodoTitle)
                        .textFieldStyle(.roundedBorder)
                    
                    Picker("优先级", selection: $selectedPriority) {
                        ForEach(TodoItem.Priority.allCases, id: \.self) { priority in
                            Text(priority.rawValue).tag(priority)
                        }
                    }
                    .pickerStyle(.menu)
                    
                    Button {
                        if !newTodoTitle.isEmpty {
                            model.addTodo(newTodoTitle, priority: selectedPriority)
                            newTodoTitle = ""
                        }
                    } label: {
                        Image(systemName: "plus.circle.fill")
                            .font(.title2)
                    }
                    .disabled(newTodoTitle.isEmpty)
                }
                .padding()
            }
            .navigationTitle("待办事项")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button {
                        model.deleteCompleted()
                    } label: {
                        Text("清除已完成")
                    }
                    .disabled(model.completedCount == 0)
                }
            }
        }
    }
    
    func priorityColor(_ priority: TodoItem.Priority) -> Color {
        switch priority {
        case .low:
            return .green.opacity(0.3)
        case .medium:
            return .yellow.opacity(0.3)
        case .high:
            return .red.opacity(0.3)
        }
    }
}

// MARK: - 4. 购物车模型

/// 商品模型
struct Product: Identifiable, Codable {
    var id: UUID = UUID()
    var name: String
    var price: Double
    var imageName: String
}

/// 购物车项目
struct CartItem: Identifiable {
    var id: UUID = UUID()
    var product: Product
    var quantity: Int = 1
    
    var totalPrice: Double {
        product.price * Double(quantity)
    }
}

/// 购物车模型
class ShoppingCartModel: ObservableObject {
    @Published var items: [CartItem] = []
    
    var totalPrice: Double {
        items.reduce(0) { $0 + $1.totalPrice }
    }
    
    var itemCount: Int {
        items.reduce(0) { $0 + $1.quantity }
    }
    
    func addItem(_ product: Product) {
        if let index = items.firstIndex(where: { $0.product.id == product.id }) {
            items[index].quantity += 1
        } else {
            items.append(CartItem(product: product))
        }
    }
    
    func removeItem(_ item: CartItem) {
        items.removeAll { $0.id == item.id }
    }
    
    func updateQuantity(_ item: CartItem, quantity: Int) {
        if let index = items.firstIndex(where: { $0.id == item.id }) {
            if quantity > 0 {
                items[index].quantity = quantity
            } else {
                removeItem(item)
            }
        }
    }
    
    func clearCart() {
        items.removeAll()
    }
}

/// 购物车视图
struct ShoppingCartModelView: View {
    @StateObject private var cart = ShoppingCartModel()
    
    let products = [
        Product(name: "苹果", price: 5.0, imageName: "apple"),
        Product(name: "香蕉", price: 3.0, imageName: "banana"),
        Product(name: "橙子", price: 4.0, imageName: "orange"),
        Product(name: "葡萄", price: 8.0, imageName: "grapes")
    ]
    
    var body: some View {
        NavigationView {
            VStack {
                // 商品列表
                List {
                    ForEach(products) { product in
                        HStack {
                            Image(systemName: "cart.fill")
                                .foregroundColor(.blue)
                            
                            VStack(alignment: .leading) {
                                Text(product.name)
                                    .font(.headline)
                                Text("¥\(String(format: "%.2f", product.price))")
                                    .font(.subheadline)
                                    .foregroundColor(.secondary)
                            }
                            
                            Spacer()
                            
                            Button {
                                cart.addItem(product)
                            } label: {
                                Image(systemName: "plus.circle.fill")
                                    .foregroundColor(.blue)
                            }
                        }
                    }
                }
                .listStyle(.plain)
                
                Divider()
                
                // 购物车
                VStack(alignment: .leading, spacing: 10) {
                    Text("购物车")
                        .font(.headline)
                        .padding(.horizontal)
                    
                    if cart.items.isEmpty {
                        Text("购物车为空")
                            .foregroundColor(.secondary)
                            .frame(maxWidth: .infinity, alignment: .center)
                            .padding()
                    } else {
                        List {
                            ForEach(cart.items) { item in
                                HStack {
                                    VStack(alignment: .leading) {
                                        Text(item.product.name)
                                        Text("¥\(String(format: "%.2f", item.totalPrice))")
                                            .font(.caption)
                                            .foregroundColor(.secondary)
                                    }
                                    
                                    Spacer()
                                    
                                    HStack {
                                        Button {
                                            cart.updateQuantity(item, quantity: item.quantity - 1)
                                        } label: {
                                            Image(systemName: "minus.circle")
                                        }
                                        
                                        Text("\(item.quantity)")
                                            .frame(width: 30)
                                        
                                        Button {
                                            cart.updateQuantity(item, quantity: item.quantity + 1)
                                        } label: {
                                            Image(systemName: "plus.circle")
                                        }
                                    }
                                }
                            }
                            .onDelete { indexSet in
                                for index in indexSet {
                                    cart.removeItem(cart.items[index])
                                }
                            }
                        }
                        .frame(height: 200)
                    }
                    
                    HStack {
                        Text("总计: ¥\(String(format: "%.2f", cart.totalPrice))")
                            .font(.headline)
                        Spacer()
                        Button("清空购物车") {
                            cart.clearCart()
                        }
                        .buttonStyle(.borderedProminent)
                        .disabled(cart.items.isEmpty)
                    }
                    .padding()
                }
            }
            .navigationTitle("购物车示例")
        }
    }
}

// MARK: - 5. 网络数据模型（模拟）

/// API 响应模型
struct APIResponse<T: Codable>: Codable {
    let success: Bool
    let data: T?
    let message: String?
}

/// 用户数据模型
struct UserData: Identifiable, Codable {
    var id: Int
    var name: String
    var email: String
    var avatar: String?
}

/// 网络数据模型
class NetworkDataModel: ObservableObject {
    @Published var users: [UserData] = []
    @Published var isLoading: Bool = false
    @Published var errorMessage: String?
    
    // 模拟网络请求
    func fetchUsers() async {
        DispatchQueue.main.async {
            self.isLoading = true
            self.errorMessage = nil
        }
        
        // 模拟网络延迟
        try? await Task.sleep(nanoseconds: 1_000_000_000)
        
        // 模拟数据
        let mockUsers = [
            UserData(id: 1, name: "张三", email: "zhangsan@example.com", avatar: nil),
            UserData(id: 2, name: "李四", email: "lisi@example.com", avatar: nil),
            UserData(id: 3, name: "王五", email: "wangwu@example.com", avatar: nil)
        ]
        
        DispatchQueue.main.async {
            self.users = mockUsers
            self.isLoading = false
        }
    }
    
    func addUser(_ user: UserData) async {
        DispatchQueue.main.async {
            self.users.append(user)
        }
    }
    
    func deleteUser(_ user: UserData) {
        users.removeAll { $0.id == user.id }
    }
}

/// 网络数据视图
struct NetworkDataModelView: View {
    @StateObject private var model = NetworkDataModel()
    
    var body: some View {
        NavigationView {
            Group {
                if model.isLoading {
                    ProgressView("加载中...")
                } else if let error = model.errorMessage {
                    VStack {
                        Text("错误: \(error)")
                            .foregroundColor(.red)
                        Button("重试") {
                            Task {
                                await model.fetchUsers()
                            }
                        }
                    }
                } else {
                    List {
                        ForEach(model.users) { user in
                            HStack {
                                VStack(alignment: .leading) {
                                    Text(user.name)
                                        .font(.headline)
                                    Text(user.email)
                                        .font(.caption)
                                        .foregroundColor(.secondary)
                                }
                                Spacer()
                            }
                        }
                        .onDelete { indexSet in
                            for index in indexSet {
                                model.deleteUser(model.users[index])
                            }
                        }
                    }
                }
            }
            .navigationTitle("用户列表")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button {
                        Task {
                            await model.fetchUsers()
                        }
                    } label: {
                        Image(systemName: "arrow.clockwise")
                    }
                }
            }
            .task {
                await model.fetchUsers()
            }
        }
    }
}

// MARK: - 6. UserDefaults 持久化模型

/// 持久化设置模型
class SettingsModel: ObservableObject {
    @Published var userName: String {
        didSet {
            UserDefaults.standard.set(userName, forKey: "userName")
        }
    }
    
    @Published var isDarkMode: Bool {
        didSet {
            UserDefaults.standard.set(isDarkMode, forKey: "isDarkMode")
        }
    }
    
    @Published var fontSize: Double {
        didSet {
            UserDefaults.standard.set(fontSize, forKey: "fontSize")
        }
    }
    
    init() {
        // 从 UserDefaults 加载数据
        self.userName = UserDefaults.standard.string(forKey: "userName") ?? ""
        self.isDarkMode = UserDefaults.standard.bool(forKey: "isDarkMode")
        self.fontSize = UserDefaults.standard.double(forKey: "fontSize") == 0 ? 16 : UserDefaults.standard.double(forKey: "fontSize")
    }
}

/// 设置视图
struct SettingsModelView: View {
    @StateObject private var settings = SettingsModel()
    
    var body: some View {
        Form {
            Section("用户信息") {
                TextField("用户名", text: $settings.userName)
            }
            
            Section("外观") {
                Toggle("深色模式", isOn: $settings.isDarkMode)
                Slider(value: $settings.fontSize, in: 12...24, step: 1) {
                    Text("字体大小")
                } minimumValueLabel: {
                    Text("12")
                } maximumValueLabel: {
                    Text("24")
                }
                Text("字体大小: \(Int(settings.fontSize))")
            }
        }
        .navigationTitle("设置")
    }
}

// MARK: - 7. Codable 持久化模型

/// Codable 数据模型
struct AppData: Codable {
    var todos: [TodoItem] = []
    var lastModified: Date = Date()
}

/// Codable 持久化模型
class CodablePersistenceModel: ObservableObject {
    @Published var data = AppData()
    
    private let fileName = "app_data.json"
    
    init() {
        loadData()
    }
    
    // 从文件加载
    func loadData() {
        guard let url = getFileURL(),
              let data = try? Data(contentsOf: url),
              let decoded = try? JSONDecoder().decode(AppData.self, from: data) else {
            return
        }
        self.data = decoded
    }
    
    // 保存到文件
    func saveData() {
        data.lastModified = Date()
        guard let url = getFileURL(),
              let encoded = try? JSONEncoder().encode(data) else {
            return
        }
        try? encoded.write(to: url)
    }
    
    private func getFileURL() -> URL? {
        let fileManager = FileManager.default
        guard let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
            return nil
        }
        return documentDirectory.appendingPathComponent(fileName)
    }
}

/// Codable 持久化视图
struct CodablePersistenceModelView: View {
    @StateObject private var model = CodablePersistenceModel()
    @State private var newTodoTitle = ""
    
    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(model.data.todos) { todo in
                        HStack {
                            Button {
                                if let index = model.data.todos.firstIndex(where: { $0.id == todo.id }) {
                                    model.data.todos[index].isCompleted.toggle()
                                    model.saveData()
                                }
                            } label: {
                                Image(systemName: todo.isCompleted ? "checkmark.circle.fill" : "circle")
                            }
                            .buttonStyle(.plain)
                            
                            Text(todo.title)
                                .strikethrough(todo.isCompleted)
                        }
                    }
                    .onDelete { indexSet in
                        model.data.todos.remove(atOffsets: indexSet)
                        model.saveData()
                    }
                }
                
                HStack {
                    TextField("新待办", text: $newTodoTitle)
                        .textFieldStyle(.roundedBorder)
                    
                    Button {
                        if !newTodoTitle.isEmpty {
                            model.data.todos.append(TodoItem(title: newTodoTitle))
                            model.saveData()
                            newTodoTitle = ""
                        }
                    } label: {
                        Image(systemName: "plus.circle.fill")
                            .font(.title2)
                    }
                }
                .padding()
            }
            .navigationTitle("持久化待办")
        }
        .onAppear {
            model.loadData()
        }
    }
}

// MARK: - 8. 环境对象模型（跨视图共享）

/// 应用主题模型
class ThemeModel: ObservableObject {
    @Published var isDarkMode: Bool = false
    @Published var accentColor: Color = .blue
    
    func toggleTheme() {
        isDarkMode.toggle()
    }
}

/// 应用状态模型
class AppStateModel: ObservableObject {
    @Published var currentUser: String? = nil
    @Published var isLoggedIn: Bool = false
    
    func login(_ username: String) {
        currentUser = username
        isLoggedIn = true
    }
    
    func logout() {
        currentUser = nil
        isLoggedIn = false
    }
}

/// 环境对象使用视图
struct EnvironmentObjectModelView: View {
    @StateObject private var theme = ThemeModel()
    @StateObject private var appState = AppStateModel()
    
    var body: some View {
        TabView {
            HomeView()
                .tabItem {
                    Label("首页", systemImage: "house.fill")
                }
            
            ProfileView()
                .tabItem {
                    Label("个人", systemImage: "person.fill")
                }
            
            SettingsView()
                .tabItem {
                    Label("设置", systemImage: "gearshape.fill")
                }
        }
        .environmentObject(theme)
        .environmentObject(appState)
    }
}

struct HomeView: View {
    @EnvironmentObject var appState: AppStateModel
    @EnvironmentObject var theme: ThemeModel
    
    var body: some View {
        NavigationView {
            VStack {
                if appState.isLoggedIn {
                    Text("欢迎, \(appState.currentUser ?? "")!")
                } else {
                    Text("请登录")
                }
            }
            .navigationTitle("首页")
        }
    }
}

struct ProfileView: View {
    @EnvironmentObject var appState: AppStateModel
    @State private var username = ""
    
    var body: some View {
        NavigationView {
            VStack {
                if appState.isLoggedIn {
                    Text("已登录为: \(appState.currentUser ?? "")")
                    Button("登出") {
                        appState.logout()
                    }
                    .buttonStyle(.borderedProminent)
                } else {
                    TextField("用户名", text: $username)
                        .textFieldStyle(.roundedBorder)
                        .padding()
                    
                    Button("登录") {
                        if !username.isEmpty {
                            appState.login(username)
                            username = ""
                        }
                    }
                    .buttonStyle(.borderedProminent)
                }
            }
            .navigationTitle("个人")
        }
    }
}

struct SettingsView: View {
    @EnvironmentObject var theme: ThemeModel
    
    var body: some View {
        NavigationView {
            Form {
                Toggle("深色模式", isOn: $theme.isDarkMode)
                
                ColorPicker("强调色", selection: $theme.accentColor)
            }
            .navigationTitle("设置")
        }
    }
}

// MARK: - 9. 表单验证模型

/// 表单验证错误
enum ValidationError: LocalizedError {
    case empty
    case tooShort(minLength: Int)
    case invalidEmail
    case passwordMismatch
    
    var errorDescription: String? {
        switch self {
        case .empty:
            return "字段不能为空"
        case .tooShort(let min):
            return "至少需要 \(min) 个字符"
        case .invalidEmail:
            return "邮箱格式无效"
        case .passwordMismatch:
            return "密码不匹配"
        }
    }
}

/// 表单模型
class FormValidationModel: ObservableObject {
    @Published var email: String = ""
    @Published var password: String = ""
    @Published var confirmPassword: String = ""
    @Published var errors: [String: String] = [:]
    
    func validateEmail() -> Bool {
        errors.removeValue(forKey: "email")
        
        if email.isEmpty {
            errors["email"] = ValidationError.empty.errorDescription
            return false
        }
        
        if !email.contains("@") || !email.contains(".") {
            errors["email"] = ValidationError.invalidEmail.errorDescription
            return false
        }
        
        return true
    }
    
    func validatePassword() -> Bool {
        errors.removeValue(forKey: "password")
        
        if password.isEmpty {
            errors["password"] = ValidationError.empty.errorDescription
            return false
        }
        
        if password.count < 6 {
            errors["password"] = ValidationError.tooShort(minLength: 6).errorDescription
            return false
        }
        
        return true
    }
    
    func validateConfirmPassword() -> Bool {
        errors.removeValue(forKey: "confirmPassword")
        
        if confirmPassword != password {
            errors["confirmPassword"] = ValidationError.passwordMismatch.errorDescription
            return false
        }
        
        return true
    }
    
    func validateAll() -> Bool {
        let emailValid = validateEmail()
        let passwordValid = validatePassword()
        let confirmPasswordValid = validateConfirmPassword()
        
        return emailValid && passwordValid && confirmPasswordValid
    }
    
    var isValid: Bool {
        errors.isEmpty && !email.isEmpty && !password.isEmpty && password == confirmPassword
    }
}

/// 表单验证视图
struct FormValidationModelView: View {
    @StateObject private var form = FormValidationModel()
    @State private var showSuccess = false
    
    var body: some View {
        Form {
            Section("注册") {
                TextField("邮箱", text: $form.email)
                    .autocapitalization(.none)
                    .keyboardType(.emailAddress)
                    .onChange(of: form.email) { _ in
                        form.validateEmail()
                    }
                
                if let error = form.errors["email"] {
                    Text(error)
                        .font(.caption)
                        .foregroundColor(.red)
                }
                
                SecureField("密码", text: $form.password)
                    .onChange(of: form.password) { _ in
                        form.validatePassword()
                    }
                
                if let error = form.errors["password"] {
                    Text(error)
                        .font(.caption)
                        .foregroundColor(.red)
                }
                
                SecureField("确认密码", text: $form.confirmPassword)
                    .onChange(of: form.confirmPassword) { _ in
                        form.validateConfirmPassword()
                    }
                
                if let error = form.errors["confirmPassword"] {
                    Text(error)
                        .font(.caption)
                        .foregroundColor(.red)
                }
            }
            
            Button("提交") {
                if form.validateAll() {
                    showSuccess = true
                }
            }
            .disabled(!form.isValid)
        }
        .alert("成功", isPresented: $showSuccess) {
            Button("确定") {}
        } message: {
            Text("表单验证通过！")
        }
    }
}

// MARK: - 10. 主模型示例视图

/// 主视图 - 展示所有 Model 示例的入口
struct SwiftUIModelExamplesView: View {
    var body: some View {
        NavigationView {
            List {
                Section("基础模型") {
                    NavigationLink("计数器模型") { CounterModelView() }
                    NavigationLink("用户信息模型") { UserModelView() }
                }
                
                Section("复杂模型") {
                    NavigationLink("待办事项模型") { TodoListModelView() }
                    NavigationLink("购物车模型") { ShoppingCartModelView() }
                }
                
                Section("数据模型") {
                    NavigationLink("网络数据模型") { NetworkDataModelView() }
                    NavigationLink("表单验证模型") { FormValidationModelView() }
                }
                
                Section("持久化") {
                    NavigationLink("UserDefaults 模型") { SettingsModelView() }
                    NavigationLink("Codable 持久化") { CodablePersistenceModelView() }
                }
                
                Section("环境对象") {
                    NavigationLink("环境对象示例") { EnvironmentObjectModelView() }
                }
            }
            .navigationTitle("SwiftUI Model 示例")
        }
    }
}

#Preview {
    SwiftUIModelExamplesView()
}

